#!coding:utf-8
# vim: tabstop=4 shiftwidth=4 softtabstop=4

from celery.result import AsyncResult
from django.db.models import Q
from rest_framework.response import Response
from cvirt.manager.models import TaskDetail
from cvirt.manager.views import NonModelBaseAPIView, NamedAPIViewMixIn,BaseListAPIView
from cvirt.manager.serializers import TaskDetailSerializer


class ActivitiesView(NamedAPIViewMixIn,BaseListAPIView):
    model = TaskDetail
    serializer_class = TaskDetailSerializer
    def _get(self,request,*args,**kwargs):
        activities = TaskDetail.objects.order_by('-time').all()[:20]
        def insert_result(a):
            a['result'] = str(AsyncResult(a['meta']['task_id']).result)
            return a
        data = self.get_serializer(activities,many=True).data
        data = map(insert_result,data)
        return Response(data)

    def alives(self,request,*args,**kwargs):
        activities = TaskDetail.objects.exclude(Q(meta__status='SUCCESS')|Q(meta__status='FAILURE')).order_by('-time')
        return Response(self.get_serializer(activities,many=True).data)
